import { downloadFiles } from "@/api/file";
import { FileTableForm } from "@/api/folder/types";

/**
 * 上传文件前的处理操作
 */
export function verifyFile(file: any, fileList: any): Boolean {
  const filesize = 500;
  const fileName = file.raw.name.split(".");
  const fileExt = fileName.at(-1) ?? "";
  const ext = [
    "jpg",
    "png",
    "doc",
    "docx",
    "xlsx",
    "pdf",
    "txt",
    "py",
    "css",
    "pptx",
    "mp4",
    "avi",
    "csv",
    "wps",
    "java",
    "js",
    "c",
    "vue",
    "ts",
    "zip",
    "exe",
    "tiff",
    "bmp",
    "jpeg",
    "svg",
    "gif",
    "dot",
    "bat",
    "psd",
    "class",
    "zip",
    "rar",
    "mpg",
    "html",
    "iso",
    "mdf",
    "jar",
  ];
  const isTypeOk = ext.includes(fileExt);
  const isSizeOk = file.raw.size / 102400 / 102400 < filesize;

  if (!isTypeOk) {
    const index = fileList.indexOf(file);
    fileList.splice(index, 1);
    ElMessage.error(`上传文件只支持 ${ext.join(" / ")} 格式！`);
    return false;
  }
  if (!isSizeOk) {
    ElMessage.error(`上传文件大小不能超过 ${filesize}MB！`);
    return false;
  }
  return true;
}
// 下载
export function downloadFilesAsync(ids: FileTableForm[]) {
  downloadFiles(ids).then((response) => {
    downloadBlob(response);
  });
}
// 定义一个函数，用于创建和下载blob对象
export function downloadBlob(response: any) {
  const blob = new Blob([response.data]);
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  const contentDisposition = response.headers["content-disposition"]; // 获取Content-Disposition中的文件名
  const encodedFilename = contentDisposition.split("filename=")[1];
  const filename = decodeURIComponent(encodedFilename); // 解码文件名
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click(); // 点击下载
  document.body.removeChild(link); // 下载完成移除元素
  URL.revokeObjectURL(url); // 释放掉blob对象
}
